
from InterfaceServer import *

from datetime import datetime
import json
from Lib.SerialPort import *
from Lib.RelayControl import *
from Lib.ExportReport import *
from Lib.Beam import *
from Lib.DataRealtimeStability import *
from Lib.Utils import *
from Lib.PIDServer import *
from Lib.Borad75 import *
from SqlData.DataEntity import *
from Lib.Auto import *
from SqlData.Business import *
import time
from threading import Lock
import threading
# import RPi.GPIO as GPIO
import uuid
import os
import random
import subprocess

beam=None
relayControl = None
borad75=None
startExperimentStepMark=False
currentTempTxt1 = None
currentTempTxt2 = None
currentTempTxt3 = None
serverTimeDiff=0
#设备状态
statusCode = 0
thread = None
thread_lock = Lock()
bindex = 0
experimentType=1
comFlag = False
ctem=23;
intlightValue=0
mainPath='/home/pi/Documents/App/TY_Photolysis'
stableTempStr=''
experiment_id=''
sygz=0
def temp_background_thread():
    global bindex
    global intlightValue
    global currentTempTxt1
    global currentTempTxt2
    global currentTempTxt3
    bindex = 0
    #环境温度值
    tempValue = '0'
    #光照值
    lightValue = '0'
    temp3='0'
    startTime=(int(time.time())) * 1000+serverTimeDiff
    #print(startExperimentStepMark)
    while startExperimentStepMark:
        kg = ''
        fq = ''
        try:
            bindex+=1
            t = time.time()
            sjc = (int(t)) * 1000+serverTimeDiff
            if((int(sjc-startTime))%(3600*1000)==0):
                currentTempTxt1.flush()
                currentTempTxt2.flush()
                currentTempTxt3.flush()
                currentTempTxt1.close()
                currentTempTxt2.close()
                currentTempTxt3.close()
                tempPath = mainPath +'/Resource/ExperimentTemp/{0}'.format(experiment_id)
                currentTempTxt1 = open('{0}/1.json'.format(tempPath),'a+')
                currentTempTxt2 = open('{0}/2.json'.format(tempPath),'a+')
                currentTempTxt3 = open('{0}/3.json'.format(tempPath),'a+')
            #温度值随机产生需要改
            tempValue=str(pidServer.temp)
            intlightValue=beam.zw
            if(intlightValue<500 and intlightValue>0):
                lightValue=str(intlightValue+10)
            intTemp=beam.gz
            if(intTemp>0 and (intTemp/1000)<10000.0):
                temp3=str(round(intTemp/1000,2))
            if(bindex == 1):
                currentTempTxt1.writelines("[[{0},{1}]".format(sjc,tempValue))
                currentTempTxt2.writelines("[[{0},{1}]".format(sjc,lightValue))
                currentTempTxt3.writelines("[[{0},{1}]".format(sjc,temp3))
            else:
                currentTempTxt1.writelines(",[{0},{1}]".format(sjc,tempValue))
                currentTempTxt2.writelines(",[{0},{1}]".format(sjc,lightValue))
                currentTempTxt3.writelines(",[{0},{1}]".format(sjc,temp3))
            currentTempTxt1.flush()
            currentTempTxt2.flush()
            currentTempTxt3.flush()
        except Exception as e :
            print(str(e))
            #socketio.emit('server_temp',str(e),namespace='/temp')
        print(stableTempStr)
        socketio.emit('server_temp', tempValue + "," + lightValue + "," + temp3 + "," + kg + "," + fq + ',' + stableTempStr,namespace='/temp')
        time.sleep(1)
    global thread
    thread = None

@app.route('/')
@app.route('/index')
def index():
    return "树莓派接口服务已经运行"

@app.route('/status')
def status():
    return str(statusCode)

@app.route('/getMacAddress')
def getMacAddress():
    mac = uuid.UUID(int = uuid.getnode()).hex[-12:]
    return ":".join([mac[e:e + 2] for e in range(0,11,2)])

@socketio.on('connect', namespace='/temp')
def socketTemp():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=temp_background_thread)

@app.route('/userLogin')
def userLogin():
    try:
        user = BllUser().login(request.args["userName"],request.args["userPwd"])
        if(user is None):
            return Utils.ResultData(0,"用户名或密码错误！")
        else:
            return Utils.ResultData(1,"登录成功！",user)
    except Exception as e:
        return '设备初始化失败，请重启仪器。'+str(e)


#新增试验接口
@app.route('/insertExperiment')
def insertExperiment():
    try:
        experiment_id = str(Utils.UUID())
        global experimentType
        experimentType=int(request.args["experiment_type"])
        global beam
        beam.updateType('a' if experimentType==1 else 'b')
        BllExperiment().insertExperiment(experiment_id,int(request.args["experiment_type"]),request.args["material_name"],float(request.args["set_temp"]),request.args["description"],request.args["user_id"],request.args["user_name"],
                              request.args['sampling_reminder'], request.args['set_light'])
        return experiment_id
    except Exception as e:
        return 'error:'+str(e)


#更新试验接口
@app.route('/updateExperiment')
def updateExperiment():
    experiment_id = request.args["experiment_id"]
    result = ''
    BllExperiment().updateExperiment(experiment_id,0,result)
    return '1'

#新增试验步骤接口
@app.route('/insertExperimentStep')
def insertExperimentStep():
    try:
        global experimentType
        global ctem
        global experiment_id
        global sygz
        experiment_id = request.args["experiment_id"]
        experimentType=int(request.args["experiment_type"])
        relayControl.fengji(True)
        Sywd = float(request.args["sywd"])  # 获取设定温度
        sygz=int(request.args["sygz"])-10
        motor.Start()
        ctem=Sywd
        print(Sywd)
        pidServer.setTem(Sywd-3)
        time.sleep(0.5)
        pidServer.stop()
        time.sleep(0.2)
        pidServer.start()
        t = time.time()
        start_time_stamp = (int(request.args["start_time_stamp"]))
        global serverTimeDiff
        serverTimeDiff =start_time_stamp- (int(t)+10) * 1000
        time_local = time.localtime((start_time_stamp / 1000))
        tempPath = mainPath +'/Resource/ExperimentTemp/{0}'.format(experiment_id)
        Utils.mkdir(tempPath)
        global currentTempTxt1
        currentTempTxt1 = open('{0}/1.json'.format(tempPath),'w+')
        global currentTempTxt2
        currentTempTxt2 = open('{0}/2.json'.format(tempPath),'w+')
        global currentTempTxt3
        currentTempTxt3 = open('{0}/3.json'.format(tempPath),'w+')

        global startExperimentStepMark
        startExperimentStepMark = True
        print('2')
        global stableTempStr
        stableTempStr='0'
        t3 = threading.Thread(target=experimentProcess,args=(experimentType,))
        t3.start()
        return ''
    except Exception as e:
        return 'error:'+ str(e)
    #return jsonify([experiment_step_id,start_time_stamp])

#停止试验接口
@app.route('/stopExperimentStep')
def stopExperimentStep():
    try:
        global startExperimentStepMark
        startExperimentStepMark=False
        time.sleep(3)
        relayControl.fengji(False)
        relayControl.yansuoji(False)
        try:
            motor.Stop()
        except :
            pass

        try:
            time.sleep(0.5)
            beam.stop()
        except :
            pass
        if(experimentType==1):
            relayControl.light1(False)
        else:
            relayControl.light2(False)
        time.sleep(0.5)
        try:
            currentTempTxt1.writelines("]")
            currentTempTxt2.writelines("]")
            currentTempTxt3.writelines("]")
            currentTempTxt1.flush()
            currentTempTxt2.flush()
            currentTempTxt3.flush()
            currentTempTxt1.close()
            currentTempTxt2.close()
            currentTempTxt3.close()
        except :
            pass
        time.sleep(0.1)
        try:
            pidServer.close()
        except :
            pass
        time.sleep(0.5)
        motor.Stop()
        relayControl.pythonBoard(False)

    except Exception as e :
        return str(e)
    return '1'

@app.route('/openWarn')
def openWarn():
    GPIO.output(25, GPIO.HIGH)
    relayControl.warn(True)
    return '1'

@app.route('/openBeep')
def openBeep():
    relayControl.fengmingqi(True)
    return '1'

@app.route('/closeBeep')
def closeBeep():
    relayControl.fengmingqi(False)
    return '1'

@app.route('/openLight')
def openLight():
    relayControl.light(True)
    return '1'

@app.route('/closeLight')
def closeLight():
    relayControl.light(False)
    return '1'

@app.route('/openMotor')
def openMotor():
    relayControl.motor(True)
    return '1'

@app.route('/closeMotor')
def closeMotor():
    relayControl.motor(False)
    return '1'

@app.route('/getExperimentInfo')
def getExperimentInfo():
    experiment_id = request.args["experiment_id"]
    return Utils.ResultData(1,"获取成功！",BllExperiment().getExperimentAllInfo(experiment_id,mainPath))


#获取试验列表接口
@app.route('/getExperimentList')
def getExperimentList():
    searchValue = request.args["searchValue"]
    list = BllExperiment().getExperimentList().filter(EntityExperiment.material_name.like('%' + searchValue + '%')).order_by(EntityExperiment.start_time.desc()).all()
    return Utils.ResultData(1,"获取成功！",list)

#获取用户列表接口
@app.route('/getUserList')
def getUserList():
    searchValue = request.args["searchValue"]
    list = BllUser().getUserList().filter(or_(EntityUser.user_name.like('%' + searchValue + '%'),EntityUser.real_name.like('%' + searchValue + '%'))).all()
    return Utils.ResultData(1,"获取成功！",list)

#删除试验信息接口
@app.route('/deleteExperiment')
def deleteExperiment():
    experiment_id = request.args["experiment_id"]
    BllExperiment().delete(EntityExperiment.experiment_id == experiment_id)
    return Utils.ResultData(1,"删除成功！")

#导出数据报表接口
@app.route('/exportReport')
def exportReport():
    try:
        uPath=Utils.getUDiskPath()
        if(uPath==""):
            return Utils.ResultData(0,"未检测到U盘！")
        experiment_id = request.args["experiment_id"]
        print(request.args.values)

        entity=BllExperiment().findEntity(experiment_id)
        jsonPath=mainPath +'/Resource/ExperimentTemp/{0}'.format(experiment_id)
        exportReport= ExportReport(entity.start_time,entity.material_name,entity.set_temp,entity.set_light,entity.sampling_reminder,entity.experiment_user_name,jsonPath)
        exportReport.save(uPath+'/光解试验仪数据报表.xlsx')
    except Exception as e :
        return Utils.ResultData(0,str(e))
    return Utils.ResultData(1,"报表导出成功！")

#通讯
@app.route('/com')
def com():
    global comFlag
    comFlag = True
    return '1'

#获取用户详情信息接口
@app.route('/getUserInfo')
def getUserInfo():
    userId = request.args["userId"]
    entity = BllUser().getUserInfo(userId)
    return Utils.ResultData(1,"获取成功！",entity)

#修改用户密码接口
@app.route('/updateUserPassword')
def updateUserPassword():
    userId= request.args["userId"]
    userPwd=request.args["userPwd"]
    entity = BllUser().getUserInfo(userId)
    entity.user_pwd = Utils.MD5(userPwd)
    BllUser().update(entity)
    return Utils.ResultData(1,"修改成功！",entity)

#删除用户接口
@app.route('/deleteUser')
def deleteUser():
    userId= request.args["userId"]
    BllUser().delete(EntityUser.user_id == userId)
    return Utils.ResultData(1,"删除成功！")

#保存用户信息接口
@app.route('/saveUser')
def saveUser():
    userId = request.args["userId"]
    userName = request.args["userName"]
    realName = request.args["realName"]
    userSex = int(request.args["userSex"])
    userRole = int(request.args["userRole"])
    userPhone = request.args["userPhone"]
    remark = request.args["remark"]
    entity = EntityUser()
    if(userId == "0"):
        entity.user_id = str(Utils.UUID())
        #默认用户密码“000000”
        entity.user_pwd = Utils.MD5("000000")
    else:
        entity = BllUser().findEntity(userId)
    entity.user_name = userName
    entity.real_name = realName
    entity.user_sex = userSex
    entity.user_role = userRole
    entity.user_phone = userPhone
    entity.remark = remark
    if(userId == "0"):
        #新增用户
        BllUser().insert(entity)
    else:
        #更新用户
        BllUser().update(entity)

    return Utils.ResultData(1,"保存成功！")

@app.route('/set')
def set():
    global startExperimentStepMark
    startExperimentStepMark = True
    return '1'
@app.route('/get')
def get():
    return str(startExperimentStepMark)

#新增试验接口
@app.route('/get1')
def get1():
    return str(bindex)

#新增试验接口
@app.route('/get2')
def get2():
    return str(pidServer.getStableTem())

#新增试验接口
@app.route('/get3')
def get3():
    try:
        return str(borad75.getStableTemp1())
    except Exception as e :
        return str(e)


#新增试验接口
@app.route('/get4')
def get4():
    return str(pidServer.listTem)

#新增试验接口
@app.route('/get5')
def get5():
    return str(borad75.listTemp1)

#新增试验接口
@app.route('/get6')
def get6():
    return stableTempStr

#新增试验接口
@app.route('/get7')
def get7():
    return str(experimentType)

#新增试验接口
@app.route('/get8')
def get8():
    return str(experimentType==1)

#新增试验接口
@app.route('/get9')
def get9():
    return str(borad75.temp1)

#新增试验接口
@app.route('/get10')
def get10():
    return str(borad75.temp1>=70)

#新增试验接口
@app.route('/get11')
def get11():
    return str(cee)

#新增试验接口
@app.route('/get12')
def get12():
    return str(pidServer.getStableTem()!=None and pidServer.getStableTem()>=75)

def comJianCe():
    global comFlag
    while True:
        relayControl.com(comFlag)
        comFlag = False
        time.sleep(3)

#shade时警报服务
def startWarn():
    relayControl.warn(True)
    time.sleep(5)
    relayControl.warn(False)

#试验控温流程
def experimentProcess(type):
    global stableTempStr
    startBeamFlag=False
    time.sleep(3)
    while startExperimentStepMark:
        if(startBeamFlag==False):
            if(pidServer.temp>23):
                relayControl.yansuoji(True)
            else:
                if(experimentType==1):
                    relayControl.light1(True)
                else:
                    relayControl.light2(True)
                time.sleep(6)
                relayControl.pythonBoard(True)
                time.sleep(6)
                try:
                    beam.setBeam(sygz)
                    time.sleep(0.1)
                    beam.setBeam(sygz)
                    time.sleep(0.1)
                    beam.setBeam(sygz)
                except :
                    pass
                time.sleep(0.5)
                try:
                    beam.start()
                except :
                    pass
                time.sleep(0.5)
                try:
                    pidServer.open()
                except :
                    pass
                startBeamFlag=True
        else:
            try:
                stableTem=pidServer.getStableTem()
                if(stableTem!=None):
                    if(stableTem>ctem-2):
                        relayControl.yansuoji(True)
                    if(stableTem<ctem-5):
                        relayControl.yansuoji(False)
                    #print('稳定温度：'+str(stableTem))
                    #print('设定温度：'+str(ctem))
                    #print('光照值：'+str(intlightValue))
                    #if(int(intlightValue)==0):
                    #     beam.setBeam(sygz)
                    if(stableTem>ctem-3 and stableTem<ctem+3 and intlightValue>60.0 and intlightValue<110.0):
                        stableTempStr='1'
            except :
                pass

        time.sleep(1)

@app.route('/motor_start')
def motor_start():
    try:
        motor.Start()
        return Utils.ResultData(0, '启动电机成功')
    except Exception as e:
        return Utils.ResultData(1, '数据异常')


# 关闭电机
@app.route('/motor_stop')
def motor_stop():
    try:
        motor.Stop()
        return Utils.ResultData(0, '关闭电机成功')
    except Exception as e:
        return Utils.ResultData(1, '数据异常')


@app.route('/capture')
def capture():
    try:
        subprocess.getoutput("fswebcam --no-banner -r 1024x600 /home/pi/Documents/App/InterfaceServer/image.jpg")
        print('获取成功。。。。')
        return '获取成功'
    except:
        pass

@app.route('/delete_capture')
def delete_capture():
    try:
        os.remove('/home/pi/Documents/App/InterfaceServer/image.jpg')
        return '删除成功'
    except Exception as e:
        print(e, 99)
        return '1'

try:
    beam=Beam('a')
    # 实例化电机类
    motor = Auto()
    pidServer = PIDServer()
    #borad75 = Borad75()
    pidServer.close()
    relayControl = RelayControl()
    relayControl.run(True)
except Exception as e:
    print(str(e))




#t1 = threading.Thread(target=comJianCe)
#t1.start()
#@app.route('/init')
#def init():







